<template>
    <div class="edu-page-warp">
        <condition-card @search="searchList" @reset="reset" label-width="110px">
            <el-row>
                <el-col :span="8">
                    <el-form-item :label="$t('label.schoolTerm')">
                        <CalendarSelect
                            v-model="queryParams.calendarId"
                            @load-done="calendarChange"
                            @change="handleChange"
                        ></CalendarSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="tutorType == 2">
                    <el-form-item label="学院">
                        <DictSelect
                            v-model="queryParams.studentFaculty"
                            :data="options.faculty"
                            filterable
                        ></DictSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="tutorType == 2">
                    <el-form-item label="专业">
                        <MyMajor
                            :faculty="queryParams.studentFaculty"
                            v-model="queryParams.professionCode"
                        ></MyMajor>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="类型">
                        <DictSelect
                            v-model="queryParams.gduideType"
                            :data="options.guideType"
                        ></DictSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="状态">
                        <DictSelect
                            v-model="queryParams.status"
                            :data="options.status"
                        ></DictSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="导师所属学院">
                        <DictSelect
                            v-model="queryParams.faculty"
                            :data="options.faculty"
                            filterable
                        ></DictSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="特殊反馈">
                        <DictSelect
                            v-model="queryParams.isSpe"
                            :data="options.isSpes"
                            filterable
                        ></DictSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="提交开始时间">
                        <el-date-picker
                            type="datetime"
                            :placeholder="$t('message.startDate')"
                            :disabled="showDetail"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            v-model="queryParams.subStartTime"
                            style="width:100%;hegiht:100:"
                            :clearable="true"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="提交结束时间">
                        <el-date-picker
                            type="datetime"
                            :placeholder="$t('message.endDate')"
                            :disabled="showDetail"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            v-model="queryParams.subEndTime"
                            style="width:100%;hegiht:100:"
                            :clearable="true"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
        </condition-card>
        <el-card shadow="never">
            <div class="edu-page-title">导师指导记录</div>
            <div class="edu-opertion-bar">
                <div class="float-left">
                    <el-col :span="8">
                        <DictSelect
                            v-model="queryParams.selectType"
                            :data="options.selectType"
                            :clearable="false"
                        ></DictSelect>
                    </el-col>
                    <KeywordInput
                        v-model="queryParams.keyword"
                        @enter="searchList"
                        :placeholder="
                            queryParams.selectType == '1' ? '按学号或姓名搜索' : '按工号或姓名搜索'
                        "
                    ></KeywordInput>
                </div>
                <div class="float-right">
                    <el-button v-if="tutorType==1" @click="handleDownLoadBatch">批量下载附件</el-button>
                    <el-button @click="deleteBatch" v-premit="'delete_guide'" type="danger">
                        批量删除
                    </el-button>
                    <el-button @click="exportTutorGuide" type="primary">
                        导出
                    </el-button>
                    <el-button
                        v-premit="'reback_guide'"                      
                        @click="summit('reback', null)"
                        type="primary"
                    >
                        批量退回
                    </el-button>
                    <el-button                         
                        v-if="btnVisible"
                        @click="updateRecord(null)"
                        type="primary"
                    >
                        新增
                    </el-button>
                </div>
            </div>
            <edu-table
                url="/api/welcomeservice/tutorGuidanceRecords/list"
                ref="mainTable"
                :order="false"
                :selection="true"
                @sort-change="sortChange"
                @selection-change="selectionChange"
            >
                <edu-table-column label="学期" prop="calendarName" min-width="180" fixed="left" />
                <edu-table-column label="学生" prop="studentName" min-width="160" fixed="left" />
                <edu-table-column
                    label="导师"
                    prop="teacherName"
                    :sortable="'custom'"
                    min-width="120"
                    fixed="left"
                >
                    <template slot-scope="scope">
                        {{ scope.row.teacherName + '(' + scope.row.teacherCode + ')' }}
                    </template>
                </edu-table-column>
                <edu-table-column
                    label="导师所属学院"
                    prop="facultyI18n"
                    :sortable="'custom'"
                    min-width="160"
                >
                    <template slot="header">
                        <el-tooltip
                            class="item"
                            effect="light"
                            content="导师所属学院"
                            placement="top"
                        >
                            <span>导师所属学院</span>
                        </el-tooltip>
                    </template>
                </edu-table-column>
                <edu-table-column
                    label="学院"
                    prop="studentFacultyI18n"
                    v-if="tutorType == 2"
                    width="120"
                />
                <edu-table-column
                    label="专业"
                    prop="professionCodeI18n"
                    v-if="tutorType == 2"
                    width="120"
                />
                <!-- <edu-table-column label="特殊反馈" prop="speStudentName" width="100" />
                <edu-table-column label="简要情况说明" prop="speContent" width="120" /> -->
                <edu-table-column label="类型" prop="gduideType">
                    <template slot-scope="scope">
                        <span v-if="scope.row.gduideType == 1">日常指导</span>
                        <span v-else>期末总结</span>
                    </template>
                </edu-table-column>
                <edu-table-column
                    label="指导时间"
                    prop="startTime"
                    :sortable="'custom'"
                    min-width="160"
                >
                    <!-- <template slot-scope="scope">
                        {{ transTime(scope.row) }}
                    </template> -->
                </edu-table-column>
                <edu-table-column label="指导地点" prop="address" width="130" />
                <edu-table-column label="指导时长" prop="hour" width="130">
                    <template slot-scope="scope">
                        {{ scope.row.hour == null ? '' : scope.row.hour + 'h' }}
                    </template>
                </edu-table-column>
                <edu-table-column label="指导内容" prop="content" width="130" />
                <edu-table-column label="附件" prop="attachmentUrl">
                    <template slot-scope="scope">
                        <el-button type="text" @click="download(scope.row.attachmentUrl)">
                            {{ scope.row.attachmentUrl }}
                        </el-button>
                    </template>
                </edu-table-column>
                <edu-table-column label="状态" prop="status">
                    <template slot-scope="scope">
                        <el-tag size="mini" v-if="scope.row.status == 0">草稿</el-tag>
                        <el-tag type="success" v-else size="mini">已提交</el-tag>
                    </template>
                </edu-table-column>
                <edu-table-column label="提交时间" prop="updateAt" min-width="170">
                    <template slot-scope="scope">
                        {{ scope.row.status == 0 ? '' : scope.row.updateAt }}
                    </template>
                </edu-table-column>
                <edu-table-column
                    :label="$t('message.operating')"
                    fixed="right"
                    min-width="180px"
                    align="center"
                >
                    <template slot-scope="scope">
                        <div v-if="btnVisible">
                            <el-button
                                type="text"
                                v-if="scope.row.status == 0"
                                @click="updateRecord(scope.row)"
                                size="mini"
                            >
                                编辑
                            </el-button>
                            <el-button
                                type="text"
                                v-if="scope.row.status == 0"
                                @click="summit('summit', scope.row)"
                                size="mini"
                            >
                                提交
                            </el-button>
                            <el-button
                                type="text"
                                v-if="scope.row.status == 0"
                                @click="deletelRecord(scope.row)"
                                size="mini"
                            >
                                删除
                            </el-button>
                            <el-button
                                type="text"
                                v-if="scope.row.status == 1"
                                @click="summit('reback', scope.row)"
                                size="mini"
                            >
                                退回
                            </el-button>
                            <!-- <el-button
                                v-premit="'detail_guide'"
                                type="text"
                                @click="deatilRecord(scope.row)"
                                size="mini"
                            >
                                详情
                            </el-button> -->
                        </div>
                    </template>
                </edu-table-column>
            </edu-table>
        </el-card>
        <!-- 新增或编辑 -->
        <edu-dialog
            :title="dialogTitle"
            width="1000px"
            ref="updateDialog"
            :auto-height="true"
            @close="resetAddForm"
        >
            <el-form
                :model="createForm"
                ref="createForm"
                label-width="125px"
                label-suffix=":"
                id="createForm"
            >
                <el-row>
                    <el-col :span="8">
                        <el-form-item
                            :label="$t('导师工号')"
                            prop="teacherCode"
                            :rules="[
                                { required: true, validator: this.checkteaCode, trigger: 'blur' }
                            ]"
                        >
                            <el-input
                                v-model="createForm.teacherCode"
                                @change="teaCodeChange"
                                placeholder="请输入"
                                :disabled="this.global.isAnyTeacher || this.isEdit ||showDetail"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item
                            :label="$t('导师姓名')"
                            prop="teacherName"
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <el-input v-model="createForm.teacherName" :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item
                            :label="$t('label.schoolTerm')"
                            prop="calendarId"
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <CalendarSelect
                                v-model="createForm.calendarId"
                                :disabled="showDetail"
                                @change="handleCalendarChange(createForm.calendarId, true)"
                            ></CalendarSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="tutorType == 2">
                    <el-col :span="8">
                        <el-form-item label="学院" prop="faculty">
                            <el-input
                                v-model="createForm.studentFacultyI18n"
                                :disabled="true"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="专业" prop="professionCode">
                            <DictSelect
                                v-model="createForm.professionCode"
                                :plzSelect="true"
                                :data="options.major"
                                @change="changeMajor"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="23">
                        <el-form-item
                            label="指导学生"
                            prop="studentIds"
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <el-checkbox
                                :indeterminate="guideIsIndeterminate"
                                :disabled="options.stuList.length === 0"
                                v-model="guideCheckAll"
                                @change="handleCheckAllChange"
                            >
                                全选
                            </el-checkbox>
                            <el-checkbox-group
                                v-model="createForm.studentIds"
                                @change="handleCheckedChange"
                            >
                                <el-checkbox
                                    v-for="student in options.stuList"
                                    :label="student.value"
                                    :key="student.value"
                                >
                                    {{ student.label }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item
                            label="类型"
                            prop="gduideType"
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'change'
                                }
                            ]"
                        >
                            <DictSelect
                                v-model="createForm.gduideType"
                                :data="options.guideType"
                                :disabled="showDetail"
                                @change="changeGType"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="createForm.gduideType == 1">
                        <el-form-item
                            label="指导时间"
                            prop="startTime"
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <el-date-picker
                                type="date"                              
                                :disabled="showDetail"
                                value-format="yyyy-MM-dd"
                                v-model="createForm.startTime"
                                style="width:100%"
                                :clearable="true"                               
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="1" v-if="createForm.gduideType == 1">
                        <span
                            style="float: left;
                          padding-top: 10px;
                          padding-left: 17px;"
                        >
                            至
                        </span>
                    </el-col>
                    <el-col :span="7" v-if="createForm.gduideType == 1">
                        <el-form-item
                            label-width="1px"
                            prop="endTime"
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <el-date-picker
                                type="date"
                                :placeholder="$t('message.endDate')"
                                :disabled="showDetail"
                                value-format="yyyy-MM-dd"
                                v-model="createForm.endTime"
                                style="width:85%;hegiht:100:"
                                :clearable="true"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row v-if="createForm.gduideType == 1">
                    <el-col :span="8">
                        <el-form-item
                            label="指导地点"
                            prop="address"
                            :rules="[{required: true,message: $t('message.inputRequired'),trigger: 'blur'}]"
                        >
                            <el-input
                                v-model="createForm.address"
                                maxlength="64"
                                :disabled="showDetail"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="指导时长(小时)" prop="hour" 
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'blur'
                                },
                                {
                                    validator: validateNumber, trigger: 'blur'
                                }
                            ]">
                            <el-input v-model="createForm.hour" maxlength="8"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="createForm.gduideType == 1">
                    <el-col :span="8" >
                        <el-form-item label="指导形式" prop="guidanceForm" :rules="[{required: true,message: $t('message.inputRequired'),trigger: 'blur'}]">
                            <el-select
                                v-model="createForm.guidanceForm"
                                placeholder="请选择"
                                :disabled="showDetail"
                            >
                                <el-option
                                    v-for="item in options.guidanceForms"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="15">
                        <el-form-item label="指导形式说明">
                            <el-input
                                v-model="createForm.guidanceFormRemark"
                                maxlength="255"
                                :disabled="showDetail"
                            ></el-input>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row>
                    <el-col :span="23">
                        <el-form-item
                            :label="createForm.gduideType == 2?'期末总结':'指导内容'"
                            prop="content"
                            :rules="[
                                {
                                    required: true,
                                    message: $t('message.inputRequired'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <el-input
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 4 }"
                                placeholder="请输入内容(类型为期末总结时，指导内容需不少于100字)"
                                v-model="createForm.content"
                                maxlength="1024"
                                :disabled="showDetail"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row>
                    <el-col :span="23">
                        <el-form-item
                            label="特殊反馈"
                            prop="speStudentIds"
                            :rules="[{ validator: this.checkSpeStu, trigger: 'change' }]"
                        >
                            <el-checkbox
                                :indeterminate="specialIsIndeterminate"
                                :disabled="options.stuList.length === 0"
                                v-model="specialCheckAll"
                                @change="handleSpecialCheckAllChange"
                            >
                                全选
                            </el-checkbox>
                            <el-checkbox-group
                                v-model="createForm.speStudentIds"
                                @change="handleSpecialCheckedChange"
                            >
                                <el-checkbox
                                    v-for="student in options.stuList"
                                    :label="student.value"
                                    :key="student.value"
                                >
                                    {{ student.label }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="23">
                        <el-form-item label="简要情况说明" prop="speContent">
                            <el-input
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 4 }"
                                placeholder="请输入内容"
                                v-model="createForm.speContent"
                                maxlength="1024"
                                :disabled="showDetail"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="附件">
                            <el-upload
                                class="upload-demo"
                                :data="{ bucketname: 'face', folderpath: 'file' }"
                                :on-remove="handleRemove"
                                multiple
                                :limit="1"
                                :disabled="showDetail"
                                :before-remove="beforeRemove"
                                :before-upload="beforeAvatarUpload"
                                :on-success="uploadSuccess"
                                action="/api/commonservice/obsfile/uploadfile"
                                :file-list="fileList"
                            >
                                <el-button size="small" type="primary" :disabled="showDetail">
                                    点击上传
                                </el-button>
                                <div slot="tip" class="el-upload__tip">
                                    只能上传jpg/png/gif/doc/docx/xlsx/xls/rar/zip格式文件，且单个文件不超过10M
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="buttons">
                <el-button @click="close(createForm)">{{ $t('message.cancel') }}</el-button>
                <el-button @click="confirm('cao')" type="primary" v-if="!showDetail">
                    {{ $t('message.save') }}
                </el-button>
                <el-button @click="confirm('summit')" type="primary" v-if="!showDetail">
                    {{ $t('message.submit') }}
                </el-button>
            </span>
        </edu-dialog>
        <el-dialog title="系统提示" :visible.sync="dialogVisible" width="400px">
            <span>返回将不会保存当前信息激活设置，是否确定？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancle">取 消</el-button>
                <el-button type="primary" @click="summitTwo">确 定</el-button>
                <el-button type="primary" @click="saveClose">保存并关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { queryDic } from 'common/src/api/dictionary'
import APIs from 'common/src/api/welcomeService/guideRecords'
import TutorListAPIs from 'common/src/api/welcomeService/tutorList'
import UTILS from 'common/src/utils/utils'
import BPIs from 'common/src/api/welcomeService/schoolRelation'
import SchoolMajorSelect from './SchoolMajorSelect'
import MyMajor from './MyMajor'
import { downloadfile } from 'common/src/api/upload'
import CPIs from 'common/src/api/welcomeService/tutorExportImport'
import { mapState } from 'vuex'
import mixin from 'common/src/mixins/index';
// 本科生导师库管理
const defaultCreateForm = {
    calendarId: null,
    studentIds: [],
    studentName: '',
    currentGrade: null,
    teacherCode: '',
    teacherName: '',
    faculty: '',
    professionCode: '',
    gduideType: '',
    status: '',
    startTime: '',
    endTime: '',
    content: '',
    hour: '',
    address: '',
    attachmentUrl: '',
    type: '',
    speStudentIds: [],
    speContent: '',
    studentFaculty: '',
    guidanceForm: '',
    guidanceFormRemark: ''
}
export default {
    name: 'TutorGuideRecords',
    mixins: [mixin],
    props: ['tutorType'],
    components: {
        SchoolMajorSelect,
        MyMajor
    },
    mounted() {
        this.getOptions()        
    },
    data() {
        return {
            dialogTitle: '',
            fileList: [],
            stuList: [],
            schList: [],
            message: '',
            dialogVisible: false,
            showDetail: false,
            showStu: false,
            options: {
                faculty: [],
                major: [],
                stuList: [],
                status: [{ label: '草稿', value: 0 }, { label: '已提交', value: 1 }],
                isSpes: [{ label: '是', value: 1 }, { label: '否', value: 0 }],
                selectType: [
                    { label: '按学生搜索', value: '1' },
                    { label: '按教师搜索', value: '2' }
                ],
                guideType: [{ label: '日常指导', value: 1 }, { label: '期末总结', value: 2 }],
                guidanceForms: [
                    { label: '个别指导', value: 1 },
                    { label: '指导社会实践', value: 2 },
                    { label: '座谈会', value: 3 },
                    { label: '读书会', value: 4 },
                    { label: '课题组研讨会', value: 5 },
                    { label: '师生午餐会', value: 6 },
                    { label: '其他', value: 0 }
                ]
            },
            flag: false,
            queryParams: {
                calendarId: null,
                studentFaculty: null,
                professionCode: null,
                gduideType: null,
                status: null,
                faculty: null,
                isSpe: null,
                subStartTime: null,
                subEndTime: null,
                selectType: '1',
                keyword: null,
                stuCondition: null,
                tutorCondition: null,
                type: null,
                ascending: null,
                descending: null
            },
            createForm: UTILS.clone(defaultCreateForm),
            isEdit: false,
            delFlag: true,
            guideCheckAll: false,
            guideIsIndeterminate: false,
            specialCheckAll: false,
            specialIsIndeterminate: false,
            selectRecords: null,
            calendarDate: [],
            defaultCalendarId: null,
            btnVisible: false,
            teacherTutorList:[]   //某导师的导师库列表
        }
    },
    computed: {
        ...mapState({
            uid: state => {
                if (state.session.mockUser) {
                    return state.session.mockUser.uid
                } else {
                    return state.session.uid
                }
            },
            uName: state => {
                if (state.session.mockUser) {
                    return state.session.mockUser.name
                } else {
                    return state.session.user.name
                }
            }
        })
    },
    methods: {
        sortChange(column, prop, order) {
            if (column.order == 'ascending') {
                // "ascending"/descending
                this.queryParams.ascending = column.prop // teacherName/facultyI18n/guideTime
                this.queryParams.descending = null
            } else if (column.order == 'descending') {
                this.queryParams.descending = column.prop
                this.queryParams.ascending = null
            }
            this.searchList()
        },
        //获取学院字典列表
        getOptions() {
            let data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_YX']
            }
            queryDic(data).then(res => {
                UTILS.fillSelect(
                    {
                        faculty: 'X_YX'
                    },
                    res.data,
                    this.options
                )
            })
            this.searchList()
        },
        findStudent(cb) {
            this.stuList = []
            this.options.stuList = []
            APIs.findStudentByTeaCode(this.tutorType, this.createForm.teacherCode).then(res => {
                if (res.code == 200 && res.data.length > 0) {
                    this.stuList = res.data
                    this.handleCalendarChange(this.createForm.calendarId, false)
                    cb && cb()
                }
            })
        },
        findMajor(cb) {
            APIs.getMajorsByTeaCode(this.tutorType, this.createForm.teacherCode).then(res => {
                this.schList = []
                if (res.code == 200) {
                    this.schList = res.data
                    this.options.major = res.data
                    this.options.major.forEach(c => {
                        c.value = c.major
                        c.label = c.majorI18n
                    })
                    if (cb) {
                        this.delFlag = false
                        cb()
                    }
                }
            })
        },
        transTime(data) {
            if (!data.startTime || !data.endTime) {
                return ''
            }
            return data.startTime + '--' + data.endTime
        },
        handleRemove(file, fileList) {
            this.fileList = fileList
        },
        beforeRemove(file, fileList) {
            if (this.flag) {
                return this.$confirm(`确定移除 ${file.name}？`)
            } else {
                return this.$confirm(`上传文件不能超过 10M!,确定移除 ${file.name}？`)
            }
        },
        beforeAvatarUpload(file) {
            this.flag = file.size / 1024 / 1024 < 10
            return this.flag
        },
        uploadSuccess(res, file, fileList) {
            this.createForm.attachmentUrl = ''
            if (res.code == 200) {
                let name = file.name
                if (res.code == 200) {
                    this.createForm.attachmentUrl = res.data[name].objectkey
                }
            }
            this.fileList = fileList
        },
        download(key) {
            downloadfile(key)
        },
        reset() {
            for (const key in this.queryParams) {
                if (key != 'selectType') this.queryParams[key] = null
            }
            this.queryParams.calendarId = this.defaultCalendarId
            this.searchList()
        },
        resetAddForm() {
            this.$refs.createForm.clearValidate()
            this.options.major = []
            this.options.stuList = []
            this.searchList()
        },
        calendarChange(data) {
            this.defaultCalendarId = this.queryParams.calendarId
            this.calendarDate = data
            this.searchList()
            this.getControl();
        },
        getStuMessage(val) {
            const item = this.stuList.filter(data => {
                if (val.includes(data.studentId)) {
                    return true
                }
                return false
            })
            if (item.length > 0) {
                //第一个学生可能存在异动，优先根据学生当前年级，找到老师匹配的tutorId
                let teacherInfo=this.teacherTutorList.find(t=>t.tutorGrade==item[0].grade);
                this.createForm.tutorId = teacherInfo?teacherInfo.id:item[0].tutorId
                const dat = []
                item.forEach(i => {
                    dat.push(i.studentName + '(' + i.studentId + ')')
                })
                this.createForm.studentName = dat.join(',')
            }
        },
        getSpeStuMessage(val) {
            if (val) {
                const item = this.stuList.filter(data => {
                    if (val.includes(data.studentId)) {
                        return true
                    }
                    return false
                })
                if (item) {
                    const dat = []
                    item.forEach(i => {
                        dat.push(i.studentName + '(' + i.studentId + ')')
                    })
                    this.createForm.speStudentName = dat.join(',')
                }
            }
        },
        summit(type, data) {
            //提交,退回
            let selection = []
            this.message = ''
            let item = { ids: [], status: '' }
            if (!data) {
                selection = this.$refs.mainTable.getCheckData('id')
            } else {
                selection.push(data.id)
            }
            if (UTILS.isEmpty(selection)) {
                this.$message({
                    type: 'warning',
                    message: '请选择退回的指导记录'
                })
                return
            }
            if (type == 'reback') {
                //退回
                item.status = 0
                this.message = '退回成功'
            } else {
                item.status = 1
                this.message = '提交成功'
            }
            item.ids = selection
            APIs.updateGuideRecord(item).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: this.message
                    })
                    this.searchList()
                }
            })
        },
        updateRecord(data) {
            this.showDetail = false
            this.resetCheckBoxStatus()
            if (!data) {
                //新增
                this.isEdit = false
                this.fileList = []
                this.showStu = false
                this.dialogTitle = this.$t('message.add')
                this.createForm = UTILS.clone(defaultCreateForm)
                this.createForm.calendarId = this.queryParams.calendarId
                if (this.global.isAnyTeacher) {
                    //当前是老师，绑定当前老师信息与学生列表
                    this.createForm.teacherCode = this.uid
                    this.createForm.teacherName = this.uName
                    this.findStudent()
                }
            } else {
                //编辑
                APIs.findGuideRecord(data.id).then(res => {
                    if (res.code == 200) {
                        this.createForm = res.data
                        this.createForm.studentIds = res.data.studentId.split(',')
                        if (res.data.speStudentId) {
                            this.createForm.speStudentIds = res.data.speStudentId.split(',')
                        } else {
                            this.createForm.speStudentIds = []
                        }
                        if (this.createForm.attachmentUrl) {
                            this.fileList = [
                                {
                                    name: this.createForm.attachmentUrl,
                                    url: '其实没啥用'
                                }
                            ]
                        }
                        this.findStudent(() => {
                            //指导学生的复选框状态
                            let checkedCount = this.createForm.studentIds.length
                            this.guideCheckAll = this.options.stuList.length === checkedCount
                            this.guideIsIndeterminate =
                                checkedCount > 0 && checkedCount < this.options.stuList.length
                            //特殊学生的复选框状态
                            checkedCount = this.createForm.speStudentIds.length
                            this.specialCheckAll = this.options.stuList.length === checkedCount
                            this.specialIsIndeterminate =
                                checkedCount > 0 && checkedCount < this.options.stuList.length
                        })
                        if (this.tutorType != 1) {
                            this.findMajor()
                        }
                    }
                })
                this.isEdit = true
                this.showStu = true
                this.dialogTitle = this.$t('message.edit')
            }
            this.$refs.updateDialog.open(() => {
                this.$refs.createForm.clearValidate()
            })
        },
        deatilRecord(data) {
            this.showDetail = true
            this.showStu = true
            this.dialogTitle = '详情'
            APIs.findGuideRecord(data.id).then(res => {
                if (res.code == 200) {
                    this.createForm = res.data
                    if (this.createForm.attachmentUrl) {
                        this.fileList = [
                            {
                                name: this.createForm.attachmentUrl,
                                url: '其实没啥用'
                            }
                        ]
                    }
                }
            })
            this.$refs.updateDialog.open()
        },
        searchList() {
            this.queryParams.stuCondition = null
            this.queryParams.tutorCondition = null
            if (this.queryParams.selectType == 1) {
                this.queryParams.stuCondition = this.queryParams.keyword
            } else {
                this.queryParams.tutorCondition = this.queryParams.keyword
            }
            this.queryParams.type = this.tutorType
            this.$refs.mainTable.search(this.queryParams)
        },
        changeGType(val) {
            if (val == 2) {
                this.createForm.startTime = null
                this.createForm.endTime = null
                this.createForm.address = null
                this.createForm.hour = null
                this.$refs.createForm.clearValidate('startTime')
                this.$refs.createForm.clearValidate('endTime')
                this.$refs.createForm.clearValidate('address')
            }
        },
        deletelRecord(data) {
            let ids = []
            ids.push(data.id)
            this.createForm.ids = ids
            this.$confirm(this.$t('common.tips.beSure'), this.$t('message.confirm'), {
                distinguishCancelAndClose: false,
                confirmButtonText: this.$t('message.confirm'),
                cancelButtonText: this.$t('message.cancel')
            }).then(() => {
                APIs.deleteGuideRecord(this.createForm).then(response => {
                    if (response.code == 200) {
                        this.$message({
                            type: 'success',
                            message: this.$t('common.tips.deleteSuccess')
                        })

                        this.searchList()
                    }
                })
            })
        },
        deleteBatch() {
            if (UTILS.isEmpty(this.selectRecords)) {
                this.$message({
                    type: 'warning',
                    message: '请选择要删除的指导记录'
                })
                return
            }
            if (this.selectRecords.some(c => 1 == c.status)) {
                this.$eduAlert('已提交的指导记录不能被选中删除')
                return
            }
            this.$confirm(this.$t('message.deleteConfirm'), this.$t('message.confirm'), {
                distinguishCancelAndClose: false,
                confirmButtonText: this.$t('message.confirm'),
                cancelButtonText: this.$t('message.cancel')
            })
                .then(() => {
                    let ids = this.selectRecords.map(record => record.id)
                    let data = {}
                    data.ids = ids
                    APIs.deleteGuideRecord(data).then(response => {
                        if (response.code == 200) {
                            this.$message({
                                type: 'success',
                                message: this.$t('common.tips.deleteSuccess')
                            })

                            this.searchList()
                        }
                    })
                })
                .catch(() => {})
        },
        close(data) {
            this.fileList = []
            if (data.id) {
                this.$refs.updateDialog.close()
            } else {
                this.dialogVisible = true
            }
        },
        cancle() {
            this.dialogVisible = false
        },
        summitTwo() {
            this.dialogVisible = false
            this.closeDialog()
        },
        saveClose() {
            this.dialogVisible = false
            this.confirm('cao')
        },
        closeDialog() {
            this.$refs.updateDialog.close()
            this.$refs.createForm.clearValidate()
            this.searchList()
        },
        confirm(type) {
            this.$refs.createForm.validate(valid => {
                if (valid) {
                    let item = UTILS.clone(this.createForm)
                    item.type = this.tutorType
                    //日常指导不需要限制，期末总结，指导内容限制字数，最少100
                    if (item.gduideType == 2 && item.content.length < 100) {
                        this.$message({
                            type: 'warning',
                            message: this.$t('tutorAuth.contentRule')
                        })
                        return
                    }
                    //日常指导，对指导时间校验
                    if(item.gduideType == 1){
                        let calendar = this.calendarDate.find(c => c.id == item.calendarId)
                        let begin_time = moment(calendar.beginDay)
                                            .subtract(7, 'days')
                                            .valueOf();
                        let end_time = calendar.endDay;
                        let now = moment(item.startTime).valueOf()                       
                        if(now > end_time || now < begin_time){
                            let calendarStartStr = moment(begin_time).format('YYYY-MM-DD');
                            let calendarEndStr = moment(end_time).format('YYYY-MM-DD');
                            this.$message({
                                type: 'warning',
                                message: this.$t(`指导时间必须处于所选学期时间 ${calendarStartStr}~${calendarEndStr} 内`)
                            });
                            return;
                        }                        
                    }                    
                    if (type == 'cao') {
                        item.status = 0
                    } else {
                        item.status = 1
                    }
                    if(item.gduideType==1){
                        item.startTime=moment(item.startTime).format("YYYY-MM-DD HH:mm:ss")
                        //item.endTime=moment(item.endTime).format("YYYY-MM-DD HH:mm:ss")
                    }
                    if (item.id) {
                        //编辑
                        if (UTILS.isEmpty(this.fileList)) {
                            item.attachmentUrl = ''
                        }
                        if (item.speStudentIds.length == 0) {
                            item.speStudentId = ''
                        }
                        APIs.editGuideRecord(item).then(response => {
                            if (response.code == 200) {
                                let message = this.$t('message.editSuccess')
                                this.$message({
                                    type: 'success',
                                    message: message
                                })
                                this.closeDialog()
                            }
                        })
                    } else {
                        //新增
                        APIs.addGuideRecord(item).then(response => {
                            if (response.code == 200) {
                                let message = this.$t('message.addSuccess')
                                this.$message({
                                    type: 'success',
                                    message: message
                                })
                                this.closeDialog()
                            }
                        })
                    }
                }
            })
        },
        exportTutorGuide() {
            let loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, .48)'
            })
            this.queryParams.type = this.tutorType
            let data = _.cloneDeep(this.queryParams)
            data.ids = this.$refs.mainTable.getCheckData().map(c => c.id)
            CPIs.exportTutorGuide(data).then(res => {
                if (res.code == 200) {
                    this.delayRequest(res.data.key, loading)
                } else {
                    loading.close()
                }
            })
        },
        async delayRequest(key, loading) {
            await new Promise(resolve => setTimeout(resolve, 3000))
            CPIs.getReportStatus(key)
                .then(res => {
                    if (res.code == 200 && res.data.status) {
                        let path = CPIs.exportLogUrl + res.data.path
                        //window.open(path);
                        window.location.href = path
                        loading.close()
                    } else {
                        this.delayRequest(key, loading)
                    }
                })
                .catch(ex => {
                    this.delayRequest(key, loading)
                })
        },
        changeMajor(val) {
            this.createForm.studentIds = []
            this.createForm.speStudentIds = []
            this.options.stuList = []
            this.resetCheckBoxStatus()
            if (val) {
                const item = this.schList.find(data => {
                    if (data.major == val) {
                        return data
                    }
                })
                if (item) {
                    this.createForm.school = item.school
                    this.createForm.studentFaculty = item.personnelCollege
                    this.createForm.studentFacultyI18n = item.personnelCollegeI18n
                }
                this.findStudentByGradeorMajor(val)
            } else {
                this.createForm.school = ''
                this.createForm.studentFacultyI18n = ''
                this.createForm.studentFaculty = ''
                if (this.tutorType == 1 && this.createForm.currentGrade) {
                    this.findStudentByGradeorMajor(val)
                } else {
                    //this.options.stuList = this.allStuOptions
                }
            }
        },
        findStudentByGradeorMajor(val) {
            this.options.stuList = []
            APIs.getStudentsByMajorByTeaCode(
                this.tutorType,
                val,
                this.createForm.currentGrade,
                this.createForm.teacherCode
            ).then(res => {
                if (res.code == 200 && res.data.length > 0) {
                    this.stuList = res.data
                    let temp = []
                    for (const stu of this.stuList) {
                        temp.push({
                            label: stu.studentName + '(' + stu.studentId + ')',
                            value: stu.studentId
                        })
                    }
                    this.options.stuList = temp
                }
            })
        },
        teaCodeChange(val) {
            if (!this.global.isAnyTeacher && val) {
                TutorListAPIs.findTutorListByVo(this.tutorType, val).then(res => {
                    if (res.code == 200 && res.data.length != 0) {
                        this.teacherTutorList=res.data;
                        this.createForm.teacherName = res.data[0].teacherName
                        this.createForm.currentGrade = null //年级
                        this.createForm.professionCode = '' //所属类
                        this.createForm.studentIds = [] //指导学生
                        this.createForm.speStudentIds = [] //特殊学生
                        if (this.tutorType != 1) {
                            this.findMajor()
                        }
                        this.findStudent(() => {
                            this.resetCheckBoxStatus()
                        })
                    } else {
                        this.createForm.teacherName = ''
                    }
                    this.$refs.createForm.validateField('teacherCode')
                })
            }
        },
        checkteaCode(rule, value, callback) {
            if (!value) {
                callback(new Error(this.$t('message.inputRequired')))
            } else if (!this.createForm.teacherName) {
                callback(new Error(this.$t('没有该工号对应的导师')))
            } else {
                callback()
            }
        },
        checkSpeStu(rule, value, callback) {
            if (value && this.createForm.studentIds) {
                if (value.some(val => this.createForm.studentIds.includes(val))) {
                    callback(new Error(this.$t('指导学生已经包含特殊学生，请修改')))
                    return
                }
            }
            callback()
        },
        handleCheckAllChange(val) {
            this.createForm.studentIds = val
                ? this.options.stuList.map(student => student.value)
                : []
            this.guideIsIndeterminate = false
            this.getStuMessage(this.createForm.studentIds)
        },
        handleCheckedChange(value) {
            let checkedCount = value.length
            this.guideCheckAll = checkedCount === this.options.stuList.length
            this.guideIsIndeterminate =
                checkedCount > 0 && checkedCount < this.options.stuList.length
            this.getStuMessage(this.createForm.studentIds)
        },
        handleSpecialCheckAllChange(val) {
            this.createForm.speStudentIds = val
                ? this.options.stuList.map(student => student.value)
                : []
            this.specialIsIndeterminate = false
            this.getSpeStuMessage(this.createForm.speStudentIds)
        },
        handleSpecialCheckedChange(value) {
            let checkedCount = value.length
            this.specialCheckAll = checkedCount === this.options.stuList.length
            this.specialIsIndeterminate =
                checkedCount > 0 && checkedCount < this.options.stuList.length
            this.getSpeStuMessage(this.createForm.speStudentIds)
        },
        resetCheckBoxStatus() {
            this.guideCheckAll = false
            this.guideIsIndeterminate = false
            this.specialCheckAll = false
            this.specialIsIndeterminate = false
        },
        selectionChange(val) {
            this.selectRecords = val
        },
        handleCalendarChange(val, reset) {
            if (this.tutorType == '1') {
                let calendar_ = this.calendarDate.find(calendar => calendar.id == val)
                if (calendar_) {
                    this.options.stuList = this.stuList
                        .filter(stu => stu.grade == calendar_.year)
                        .map(stu => {
                            return {
                                label: stu.studentName + '(' + stu.studentId + ')',
                                value: stu.studentId
                            }
                        })
                }
            } else {
                this.options.stuList = this.stuList.map(stu => {
                    return {
                        label: stu.studentName + '(' + stu.studentId + ')',
                        value: stu.studentId
                    }
                })
            }
            if (reset) {
                this.createForm.studentIds = []
                this.createForm.speStudentIds = []
                this.resetCheckBoxStatus()
            }
        },
        validateNumber(rule, value, callback){
            if(isNaN(value)){
                callback(new Error("必须是数字"));
            }else{
                callback();
            }
        },
        getControl(){
            if (this.tutorType == 1) {
                this.btnVisible = false
                TutorListAPIs.getGuidanceRecordsControl({
                    calendarId:this.queryParams.calendarId,
                    type:1,
                    status:1
                }).then(res => {
                    if (res.code == 200&&res.data&&res.data.length>0) {
                        this.btnVisible = true
                    }
                })
            } else {
                this.btnVisible = true
            }
        },
        handleChange(){
            this.getControl();
        },
        handleDownLoadBatch(){
            let param=null;
            if(this.selectRecords&&this.selectRecords.length>0){
                param={ids:this.selectRecords.map(r=>r.id)}
            }else{
                param=this.queryParams;
            }
            window.location.href=APIs.getDownloadZipUrl()+"?param="+JSON.stringify(param) 
        }
    }
}
</script>
<style lang="scss" scoped>
#createForm ::v-deep .el-checkbox-group {
    .el-checkbox + .el-checkbox {
        margin-left: 0;
    }
    .el-checkbox {
        margin-right: 30px;
    }
}
</style>
